<?php
/*
 * @Author: 乔
 * @Date: 2021-10-09 14:19:06
 * @LastEditTime: 2021-11-05 10:42:25
 * @LastEditors: 乔
 * @FilePath: \tp30\app\admin\controller\Login.php
 */

namespace app\admin\controller;

use app\admin\model\Admin;
use app\BaseController;
use mailer\tp6\Mailer;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\View;

class Login extends BaseController
{
    protected function initialize()
    {
    }
    public function register()
    {
        if (Request::isPost()) {
            $post = input('post.');
            $num = \app\admin\model\Admin::where('name', '=', $post['name'])->count();
            if ($num > 0) {
                $this->error('用户名已被占用');
            }
            try {
                validate(\app\admin\validate\Login::class)
                    ->scene('register')
                    ->check($post);
                list($upReg, $path) = Upload::upload('img', true, 'images');
                if ($upReg) {
                    $post['headimg'] = $path;
                }
                $post['addtime'] = time();
                $post['pwd'] = md5($post['password']);
                list($reg, $msg) =  \app\admin\model\Admin::addInfo($post);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($reg) {
                if ($upReg) Upload::removeImg($path);
                $this->success('注册成功 正在跳转登录页', url('login'));
            }
        }
        return view();
    }
    public function resPwd()
    {
        $get = Request::get();
        if (Request::isPost()) {
            $post = input('post.');
            try {
                validate(\app\admin\validate\Login::class)
                    ->scene('resPwd')
                    ->check($post);
                $where = [];
                $where['name'] = $post['name'];
                $where['email'] = $post['email'];
                $list =  \app\admin\model\Admin::findAdminList($where);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($list) {
                $num = rand(100000, 999999);
                $res = Message::resPwdEmail($post['email'], $num);
                Cache::set($post['name'] . 'ResPwd', $num, 120);
                $this->success("邮箱验证码已发送-请在120秒内完成操作", url('Login/resPwd', ['name' => $post['name']]));
            }
        }
        if (isset($get['pwdCode']) && isset($get['name']) && Request::isGet()) {
            $num = cache('adminResPwd');
            if ($get['pwdCode'] == $num) {
                $nbr = rand(100000, 999999);
                $date = [
                    'pwd' => md5($nbr),
                ];
                $listRes =  \app\admin\model\Admin::where('name', '=', $get['name'])->update($date);
                if ($listRes) {
                    echo "<script>alert('您的密码重置为${nbr}.请尽快更改您的密码');</script>";
                    $this->success("正在返回登录页面", url('Login/login'));
                }
            }
        }

        View::assign($get);
        return view();
    }
    public function login()
    {
        // cookie('errLogin', null);
        // echo '<pre>';
        // echo print_r(cookie(''));
        // echo '<pre/>';
        if (Cookie::has('id')) {
            $id = cookie('id');
            $list = Admin::getInfo($id);
            $list = $list->toArray();
            session(md5('user'), $list);
            return redirect((string) url('admin/Index/index'));
        }
        if (Request::isPost()) {
            if (cookie('errLogin') == "errLogin") {
                $this->error("错误次数过多请一天后再试");
            }
            $post = input('post.');
            try {
                validate(\app\admin\validate\Login::class)->scene('login')->check($post);
                $where = [];
                if (!empty($post['name'])) $where['name'] = $post['name'];
                if (!empty($post['password'])) $where['pwd'] = md5($post['password']);
                $list = \app\admin\model\Admin::findAdminList($where);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($list) {
                session(md5('user'), $list->toArray());
                $msg = '登录成功，尊敬的' . $list->toArray()['name'] . '用户你好';
                cookie('errPwd', null);
                if (isset($post['trday'])) {
                    cookie('id', $list['id'], 86400);
                }
                $this->success($msg, url('Index/index'));
            } else {
                // if (!Cache::has($post['name'].'_error_number')) {
                //     Cache::set($post['name'].'_error_number',1,3600);
                // }else{
                //     Cache::inc($post['name'].'_error_number');
                // }
                if (cookie('errPwd') <> "") {
                    $num = cookie('errPwd') + 1;
                    cookie('errPwd', $num);
                    if (cookie('errPwd') > 4) {
                        cookie('errLogin', 'errLogin', 2592000);
                    }
                } else {
                    cookie('errPwd', '1', 3600);
                }
                $this->error("用户名或密码错误，请重试");
            }
        }
        View::assign('cookie', cookie('errPwd'));
        return view();
    }
    public function loginOut()
    {
        session(md5('user'), null);
        cookie('id', null);
        $this->success("退出登录成功正在返回登录页面", url('Login/login'));
    }
    public function ajaxLogin()
    {
        $code = input('post.');
        if (captcha_check($code, false)) {
            return "验证成功";
        } else {
            return "验证失败";
        }
        // try {
        //     validate(\app\admin\validate\Login::class)->scene('code')->check($code);
        // } catch (ValidateException $e) {
        //     return $e->getError();
        // } catch (\Exception $e) {
        //     return $e->getMessage();
        // }
        // return "验证成功";
    }
    public function ajaxName()
    {
        $name = input('post.user');
        $num = Cache::get($name . '_error_number');
        if ($num < 3) {
            return 1;
        } else {
            return 0;
        }
    }
}
